package com.helu.lubike.activity;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import com.helu.lubike.R;
import com.helu.lubike.databinding.ActivityBtSearchingBinding;
import com.helu.lubike.utils.Utils;
import com.helu.lubike.viewmodel.BTSearchingViewModel;

import java.util.Timer;
import java.util.TimerTask;

/**
 * @author helu  17-2-10 上午9:27
 * @description 蓝牙连续测据Activity
 */

public class BTSearchingActivity extends AppCompatActivity {

    private static final String MSG = "BTSearchingActivity";
    private ActivityBtSearchingBinding inflate;

    /**
     * 蓝牙模块的地址
     */
    private String btAddress;
    private BluetoothAdapter mBluetoothAdapter;
    private BluetoothDevice remoteDevice;
    private Timer mRssiTimer;
    private IntentFilter mFilter;


    private BroadcastReceiver mReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                Log.d(MSG, "device name: " + name);
                int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);
                switch (state) {
                    case BluetoothDevice.BOND_NONE:
                        Log.d(MSG, "BOND_NONE 删除配对");
                        break;
                    case BluetoothDevice.BOND_BONDING:
                        Log.d(MSG, "BOND_BONDING 正在配对");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        if (remoteDevice.getName().equals(device.getName())) {
                            Log.d(MSG, "BOND_BONDED 配对成功");
                            statTask();
                        }
                        break;
                }
            }
        }
    };
    private BTSearchingViewModel mViewModel;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        inflate = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_bt_searching, null, false);
        mViewModel = new BTSearchingViewModel();
        inflate.setViewModel(mViewModel);
        setContentView(inflate.getRoot());
        initView();
        initData();
        initListener();

    }

    private void initListener() {
        inflate.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        inflate.yueding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.showToast(BTSearchingActivity.this, "点击了预定按钮");
            }
        });
    }

    private void initView() {
        mViewModel.initChart(inflate.lineChart);
    }

    private void initData() {
        btAddress = getIntent().getStringExtra("address");
        if (btAddress == null) {
            Utils.showToast(this, "找车失败");
            finish();
        }

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        remoteDevice = mBluetoothAdapter.getRemoteDevice(btAddress);

        // 注册搜索完时的receiver
        mFilter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        registerReceiver(mReceiver, mFilter);

        if (remoteDevice != null) {
            inflate.title.setText("蓝牙定位(" + remoteDevice.getName() + ")");

            if (remoteDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
                Log.d(MSG, "该设备已经完成配对");
                statTask();
            } else {
                remoteDevice.createBond();      //去配对
            }

        }

    }

    /**
     * 初始化完成,开始不断的测量Rssi 和 预约车辆
     */
    private void statTask() {
        remoteDevice.connectGatt(this, false, new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(final BluetoothGatt gatt,
                                                int status, int newState) {

                super.onConnectionStateChange(gatt, status, newState);

                Log.d(MSG, "onConnectionStateChange;" + newState);

                if (newState == BluetoothProfile.STATE_CONNECTED) {
                    //连接成功时获取特征值
                    gatt.discoverServices();
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            //我不停的读取，不停的读取，时间频率自己控制就行
                            gatt.readRemoteRssi();
                        }
                    };
                    mRssiTimer = new Timer();
                    mRssiTimer.schedule(task, 1000, 1000);
                } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                    if (mRssiTimer != null) {
                        mRssiTimer.cancel();
                    }
                }
            }

            @Override
            public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {
                // 动态获取 rssi 值
                Log.d(MSG, "RSSI值是:" + rssi);
                mViewModel.addRssi(rssi);
            }

            @Override
            // New services discovered
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                if (status == BluetoothGatt.GATT_SUCCESS) {
                    Log.d(MSG, "onServicesDiscovered");
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mRssiTimer != null) {
            mRssiTimer.cancel();
        }

        //解除注册
        unregisterReceiver(mReceiver);
        mViewModel.destroy();
    }
}
